package com.i2863.shiroDemo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.i2863.shiroDemo.annotation.SysLog;
import com.i2863.shiroDemo.dto.UserInfo;
import com.i2863.shiroDemo.entity.Log;
import com.i2863.shiroDemo.mapper.LogMapper;
import com.i2863.shiroDemo.service.ILogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

@Service
public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements ILogService {

    @Override
    @Async("asyncServiceExecutor")
    public void addLog(JoinPoint joinPoint, UserInfo userInfo) {
        // 请求参数
        Object[] args = joinPoint.getArgs();
        String requestParam = "";
        if (args != null && args.length > 0) {
            try {
                requestParam = args[0].toString();
            } catch (Exception ignored) {

            }
        }

        // 添加系统操作日志
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method targetMethod = methodSignature.getMethod();
        SysLog sysLog = targetMethod.getAnnotation(SysLog.class);
        if (sysLog != null) {
            Log log = new Log();
            log.setUserId(userInfo.getId());
            log.setUserName(userInfo.getUserName());
            log.setOperMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.setRequestParam(requestParam);
            log.setOperDesc(sysLog.value());
            this.save(log);
        }
    }
}
